package com.develop.alarm.controller;

import com.develop.alarm.domain.RealtimealarmDO;
import com.develop.alarm.service.RealtimealarmService;
import com.develop.common.utils.PageUtils;
import com.develop.common.utils.Query;
import com.develop.common.utils.R;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 
 * 
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2019-06-26 15:05:00
 */
 
@Controller
@RequestMapping("/domain/realtimealarm")
public class RealtimealarmController {
	@Autowired
	private RealtimealarmService realtimealarmService;
	
	@GetMapping()
//	@RequiresPermissions("domain:realtimealarm:realtimealarm")
	String Realtimealarm(){
	    return "alarm/realtimealarm";
	}

    /**
     * 报警列表
     * @param params
     * @return
     */
	@ResponseBody
	@GetMapping("/list")
//	@RequiresPermissions("domain:realtimealarm:realtimealarm")
	public PageUtils list(@RequestParam Map<String, Object> params){
        params = this.formatTime(params);

        //查询列表数据
        Query query = new Query(params);
		List<RealtimealarmDO> realtimealarmList = new ArrayList<>();
		int total = 0;
        if ("1".equals(params.get("alarmstatus"))){
			realtimealarmList = realtimealarmService.activeList(query);
			total = realtimealarmService.activeCount(query);
		}else {
			realtimealarmList = realtimealarmService.list(query);
			total = realtimealarmService.count(query);
		}

		PageUtils pageUtils = new PageUtils(realtimealarmList, total);
		return pageUtils;
	}


    /**
     * 各个告警级别的个数展示
     * @param params
     * @return
     */
	@ResponseBody
	@GetMapping("/count")
//	@RequiresPermissions("domain:realtimealarm:realtimealarm")
	public PageUtils count(@RequestParam Map<String, Object> params){
        params = this.formatTime(params);
		//查询列表数据
		Query query = new Query(params);
		int total = 0;
		if ("1".equals(params.get("alarmstatus"))){
			total = realtimealarmService.activeCount(query);
		}else {
			total = realtimealarmService.count(query);
		}
		PageUtils pageUtils = new PageUtils(null, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
//	@RequiresPermissions("domain:realtimealarm:add")
	String add(){
	    return "alarm/add";
	}

	@GetMapping("/edit/{alarmseq}")
//	@RequiresPermissions("domain:realtimealarm:edit")
	String edit(@PathVariable("alarmseq") Long alarmseq,Model model){
		RealtimealarmDO realtimealarm = realtimealarmService.get(alarmseq);
		model.addAttribute("realtimealarm", realtimealarm);
	    return "alarm/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
//	@RequiresPermissions("domain:realtimealarm:add")
	public R save(RealtimealarmDO realtimealarm){
		if(realtimealarmService.save(realtimealarm)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
//	@RequiresPermissions("domain:realtimealarm:edit")
	public R update(RealtimealarmDO realtimealarm){
		realtimealarmService.update(realtimealarm);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
//	@RequiresPermissions("domain:realtimealarm:remove")
	public R remove(Long alarmseq){
		if(realtimealarmService.remove(alarmseq)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
//	@RequiresPermissions("domain:realtimealarm:batchRemove")
	public R remove(@RequestParam("ids[]") Long[] alarmseqs){
		realtimealarmService.batchRemove(alarmseqs);
		return R.ok();
	}

	/**
	 * 导出功能
	 *
	 * @param request
	 * @param response
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/export", method = {RequestMethod.GET,
			RequestMethod.POST}, produces = "text/plain; charset=utf-8")
	@ResponseBody
	public String export(HttpServletRequest request, HttpServletResponse response,
						 @RequestParam Map<String, Object> params) throws Exception {
		params = this.formatTime(params);

		String[] excelHeader = {"序号", "告警ID", "省份", "网元类型", "网元名称", "告警对象", "告警级别","告警标题","告警发生时间","具体问题"};
//        if ("1".equals(status)||"2".equals(status)||"3".equals(status)){
//            excelHeader = Arrays.copyOf(excelHeader,excelHeader.length+1);
//            excelHeader[excelHeader.length-1]="状态";
//        }
		String name = "告警查询";
		String title = "告警查询";
//		Query query = new Query(params);

		List<RealtimealarmDO> realtimealarmList = realtimealarmService.list(params);


		response.setContentType("application/vnd.ms-excel");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String CTime = sdf.format(new Date());
		response.setHeader("Content-disposition",
				"attachment;filename=" + new String(name.getBytes("gb2312"), "ISO8859-1") + CTime + ".xls");
		OutputStream ouputStream = response.getOutputStream();
		HSSFWorkbook wb = this.exportDatas(realtimealarmList, title, excelHeader);
		wb.write(ouputStream);
		ouputStream.flush();
		ouputStream.close();
		return null;
	}

	private HSSFWorkbook exportDatas(List<RealtimealarmDO> list, String title, String[] excelHeader) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("sheet1");
		HSSFCellStyle style = wb.createCellStyle();
		HSSFCellStyle style0 = wb.createCellStyle();
		HSSFCellStyle keystyle = wb.createCellStyle();
		style0.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
		style0.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
		HSSFRow row = sheet.createRow(0);
		HSSFCell cell0 = row.createCell(0);
		HSSFFont font = wb.createFont();
		// font.setColor(HSSFColor.RED.index); //HSSFColor.RED.index //字体颜色
		// font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体增粗
		font.setFontHeightInPoints((short) 12);
		style0.setFont(font);
		cell0.setCellValue(title);
		cell0.setCellStyle(style0);
		CellRangeAddress cra = new CellRangeAddress(0, 0, 0, 9);// 传入合并单元格的首行、最后一行、首列、最后一列
		sheet.addMergedRegion(cra);

		style.setAlignment(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_LEFT); // 左居中
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中

		keystyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
		keystyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
		HSSFFont keyfont = wb.createFont();
		// keyfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体增粗
		keyfont.setFontHeightInPoints((short) 10);
		keystyle.setFont(keyfont);

		// 创建第一行
		row = sheet.createRow(1);
		for (int i = 0; i < excelHeader.length; i++) {
			HSSFCell cell = row.createCell(i);
			cell.setCellValue(excelHeader[i]);
			cell.setCellStyle(style);
			sheet.setColumnWidth(i, (excelHeader[i].getBytes().length) * 360); // 按照字体设置列宽度
			font = wb.createFont();
			// font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体增粗
			style.setFont(font);
		}
		// 循环插入数据
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				RealtimealarmDO realtimealarmDO = list.get(i);
				row = sheet.createRow(i + 2);
				row.createCell(0).setCellValue(i + 1);
				row.createCell(1).setCellValue(realtimealarmDO.getAlarmseq());
				row.createCell(2).setCellValue(realtimealarmDO.getProvince());
				row.createCell(3).setCellValue(realtimealarmDO.getNetype());
				row.createCell(4).setCellValue(realtimealarmDO.getNename());
				row.createCell(5).setCellValue(realtimealarmDO.getRnetype());
				row.createCell(6).setCellValue(realtimealarmDO.getAlarmtitle());
				row.createCell(7).setCellValue(realtimealarmDO.getOrigseverity());
				row.createCell(8).setCellValue(realtimealarmDO.getEventtime());
				row.createCell(9).setCellValue(realtimealarmDO.getLocationinfo());

//                row.createCell(6).setCellValue(termDOVO.getDepict());
//                row.createCell(7).setCellValue(sdf.format(termDOVO.getAddtime()));
			}
		}
		return wb;
	}

	private Map<String, Object> formatTime(Map<String, Object> params){
        SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String beginTime = (String)params.get("beginTime");
        String endTime = (String)params.get("endTime");
        try {
            if (!"".equals(beginTime)){
                Date parse1 = format2.parse(beginTime);
                beginTime =format1.format(parse1);
            }
            if (!"".equals(endTime)){
                Date parse2 = format2.parse(endTime);
                endTime =format1.format(parse2);
            }
            params.put("beginTime",beginTime);
            params.put("endTime",endTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return params;
    }
	
}
